<?php

namespace App\Admin\Controllers\Wechat;

use App\Models\Wechat;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use \EasyWeChat;

class MenuController extends Controller
{
    use HasResourceActions;
    protected $header = '微信公众号--菜单管理';

    protected $config_menu = NULL;

    public function __construct()
    {
        $this->config_menu = Wechat\Config::where('name', 'menu')->first();
    }

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header($this->header);
            $content->description('description');

            $config_menu = $this->config_menu;

            $response_row = Wechat\Response::all();
            $response_list = [];
            foreach ($response_row as $key => $value) {
                $response_list[$value['eventkey']] = $value['title'];
            }

            $content->body(view('admin.wechat.menu', compact('response_list', 'config_menu')));
        });
    }

    /**
     * 修改
     */
    public function edit(Request $request)
    {
        $menu = $request->menu;
        $menu = (array)json_decode($menu, TRUE);

        foreach ($menu as $index => &$item) {
            if (isset($item['sub_button'])) {
                foreach ($item['sub_button'] as &$subitem) {

                    if (!isset($item['type']))
                        $item['type'] = 'click';

                    if ($subitem['type'] == 'view') {
                        $allowFields = ['type', 'name', 'url'];
                        $subitem = ['type' => $subitem['type'], 'name' => $subitem['name'], 'url' => @$subitem['url']];
                    } else if ($subitem['type'] == 'miniprogram') {
                        $allowFields = ['type', 'name', 'url', 'appid', 'pagepath'];
                        $subitem = ['type' => $subitem['type'], 'name' => $subitem['name'], 'url' => @$subitem['url'], 'appid' => $subitem['appid'], 'pagepath' => $subitem['pagepath']];
                    } else {
                        $allowFields = ['type', 'name', 'key'];
                        $subitem = ['type' => $item['type'], 'name' => $subitem['name'], 'key' => $subitem['key']];
                    }

                    $subitem = array_intersect_key($subitem, array_flip($allowFields));
                }
            } else {
                if ($item['type'] == 'view') {
                    $allowFields = ['type', 'name', 'url'];
                } else if ($item['type'] == 'miniprogram') {
                    $allowFields = ['type', 'name', 'url', 'appid', 'pagepath'];
                } else {
                    $allowFields = ['type', 'name', 'key'];
                }
                $item = array_intersect_key($item, array_flip($allowFields));
            }
        }

        $this->config_menu->value = json_encode($menu, JSON_UNESCAPED_UNICODE);
        $this->config_menu->save();

        return response()->json([
            'code' => 1,
            'msg' => '',
            'data' => []
        ]);

    }

    public function sync()
    {
        $app = EasyWeChat::officialAccount(); // 公众号

//        $list = $app->menu->list();
////        dd($list);

        try {
            $hasError = false;
            $menu = json_decode($this->config_menu->value, TRUE);
            foreach ($menu as $k => $v) {
                if (isset($v['sub_button'])) {
                    foreach ($v['sub_button'] as $m => $n) {
                        if ($n['type'] == 'click' && isset($n['key']) && !$n['key']) {
                            $hasError = true;
                            break 2;
                        }
                    }
                } else if ($v['type'] == 'click' && isset($v['key']) && !$v['key']) {
                    $hasError = true;
                    break;
                }
            }

            if (!$hasError) {
                try {

                    $res = $app->menu->create($menu);

                    if ($res && $res['errcode'] == 0) {
                        return response()->json([
                            'status_code' => 1,
                            'message' => '发布成功'
                        ]);
                    } else {
                        return response()->json([
                            'status_code' => 0,
                            'message' => '发布失败',
                            'data' => $res
                        ]);
                    }

                } catch (\EasyWeChat\Core\Exceptions\HttpException $e) {

                }

            } else {
                return response()->json([
                    'status_code' => 0,
                    'message' => '格式有误'
                ]);
            }

        } catch (\Exception $e) {

        }

        return response()->json([
            'status_code' => 0,
            'message' => '发布失败'
        ]);
    }

}
